<template>
  <div class="search-container">
    <el-input
      v-model="query"
      placeholder="请输入搜索内容"
      class="enhanced-search-input"
      @keyup.enter="handleSearch"
      :debounce="300"
    >
      <template #append>
        <el-icon @click="handleSearch">
          <Search />
        </el-icon>
      </template>
    </el-input>

    <!-- 历史搜索 -->
    <div v-if="historyList.length" class="history">
      <h4>历史搜索</h4>
      <el-tag
        v-for="(item, index) in historyList"
        :key="index"
        closable
        @close="removeHistory(item)"
        @click="selectHistory(item)"
      >
        {{ item }}
      </el-tag>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted } from "vue";
import { ElMessage } from "element-plus";
import { Search } from "@element-plus/icons-vue";

const query = ref(""); // 搜索关键词
const historyList = ref([]); // 历史搜索列表

// 从 localStorage 加载历史搜索
onMounted(() => {
  const storedHistory = localStorage.getItem("searchHistory");
  if (storedHistory) {
    historyList.value = JSON.parse(storedHistory);
  }
});

// 搜索逻辑
const handleSearch = () => {
  if (query.value.trim()) {
    saveHistory(query.value.trim());
    console.log("Searching for:", query.value);
    // 在这里实现你的搜索逻辑
  }
};

// 保存历史记录
const saveHistory = (value) => {
  if (historyList.value.indexOf(value) === -1) {
    historyList.value.unshift(value);
    historyList.value = historyList.value.slice(0, 10); // 限制最多保存 10 条
    localStorage.setItem("searchHistory", JSON.stringify(historyList.value));
  }
};

// 删除历史记录
const removeHistory = (item) => {
  const index = historyList.value.indexOf(item);
  if (index !== -1) {
    historyList.value.splice(index, 1);
    localStorage.setItem("searchHistory", JSON.stringify(historyList.value));
  }
};

// 选择历史记录
const selectHistory = (item) => {
  query.value = item;
};
</script>

<style scoped>
.search-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  background-color: #f7f7f7;
  padding: 20px;
}

.enhanced-search-input {
  width: 100%;
  max-width: 600px;
  height: 70px;
  border-radius: 35px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
  background-color: #ffffff;
  font-size: 16px;
}

.history {
  margin-top: 20px;
}

.history h4 {
  font-size: 14px;
  margin-bottom: 5px;
}

.el-tag {
  margin-right: 5px;
  cursor: pointer;
}

@media (max-width: 768px) {
  .search-container {
    background-color: #ffffff;
    background: url("@/assets/mbg.jpg") no-repeat center center;
    background-size: cover;
  }

  .enhanced-search-input {
    width: 90%;
    max-width: 100%;
  }
}
</style>